package com.shardingjdbc.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @author by itheima
 * @Date 2022/1/19
 * @Description 定义t_order表的映射策略
 */
public class PreciseTBShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     * 所有数据库集合
     * @param collection 所有物理数据库名称集合
     * @param preciseShardingValue 传入的片键值
     * @return 返回可访问的数据库
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        Long key = preciseShardingValue.getValue();
        int index=(key.intValue() % 2) +1 ;
        //获取以指定的index结尾的table的名称
        String name = collection.stream().filter(dbName -> dbName.endsWith("_" + index)).findFirst().get();
        return name;
    }
}
